using Microsoft.EntityFrameworkCore;
using GroupSix.Domain.Entity.App;
using GroupSix.Domain.Repositories;
using GroupSix.Domain.common;
using GroupSix.Infrastructure.Data;

namespace GroupSix.Infrastructure.Reposoitories;

/// <summary>
/// 菜单仓库实现
/// </summary>
public class MenuRepository : EfRepository<GsMenu>, IMenuRepository
{
    public MenuRepository(GroupSixDbContext context) : base(context)
    {
    }

    /// <summary>
    /// 检查菜单名称是否存在
    /// </summary>
    public async Task<bool> IsMenunameExistsAsync(string menuname, Guid? excludeId = null)
    {
        var query = _tb.Where(m => m.Menuname == menuname && !m.IsDeleted);
        
        if (excludeId.HasValue)
        {
            query = query.Where(m => m.Id != excludeId.Value);
        }

        return await query.AnyAsync();
    }

    /// <summary>
    /// 检查菜单路径是否存在
    /// </summary>
    public async Task<bool> IsMenuPathExistsAsync(string menuPath, Guid? excludeId = null)
    {
        var query = _tb.Where(m => m.MenuPath == menuPath && !m.IsDeleted);
        
        if (excludeId.HasValue)
        {
            query = query.Where(m => m.Id != excludeId.Value);
        }

        return await query.AnyAsync();
    }

    /// <summary>
    /// 根据名称获取菜单
    /// </summary>
    public async Task<GsMenu?> GetByMenunameAsync(string menuname)
    {
        return await _tb.FirstOrDefaultAsync(m => m.Menuname == menuname && !m.IsDeleted);
    }

    /// <summary>
    /// 根据路径获取菜单
    /// </summary>
    public async Task<GsMenu?> GetByMenuPathAsync(string menuPath)
    {
        return await _tb.FirstOrDefaultAsync(m => m.MenuPath == menuPath && !m.IsDeleted);
    }

    /// <summary>
    /// 分页获取菜单列表
    /// </summary>
    public async Task<PageResult<GsMenu>> GetPagedAsync(int pageIndex, int pageSize, string? menuname = null, string? menuPath = null, Guid? parentId = null)
    {
        var query = _tb.Where(m => !m.IsDeleted);

        // 按菜单名称搜索
        if (!string.IsNullOrEmpty(menuname))
        {
            query = query.Where(m => m.Menuname.Contains(menuname));
        }

        // 按菜单路径搜索
        if (!string.IsNullOrEmpty(menuPath))
        {
            query = query.Where(m => m.MenuPath != null && m.MenuPath.Contains(menuPath));
        }

        // 按父菜单ID筛选
        if (parentId.HasValue)
        {
            query = query.Where(m => m.ParentId == parentId.Value);
        }
        else
        {
            // 如果没有指定父菜单ID，则获取根菜单
            query = query.Where(m => m.ParentId == null);
        }

        // 按排序和创建时间排序
        query = query.OrderBy(m => m.Order).ThenBy(m => m.CreatedAt);

        var totalCount = await query.CountAsync();
        var items = await query
            .Skip((pageIndex - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        return new PageResult<GsMenu>
        {
            Items = items,
            TotalCount = totalCount,
            PageIndex = pageIndex,
            PageSize = pageSize
        };
    }

    /// <summary>
    /// 获取菜单树
    /// </summary>
    public async Task<List<GsMenu>> GetMenuTreeAsync()
    {
        return await _tb
            .Where(m => !m.IsDeleted)
            .Include(m => m.Children.Where(c => !c.IsDeleted))
            .OrderBy(m => m.Order)
            .ThenBy(m => m.CreatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 获取指定父菜单的子菜单
    /// </summary>
    public async Task<List<GsMenu>> GetChildrenAsync(Guid? parentId)
    {
        return await _tb
            .Where(m => m.ParentId == parentId && !m.IsDeleted)
            .OrderBy(m => m.Order)
            .ThenBy(m => m.CreatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 检查菜单是否有子菜单
    /// </summary>
    public async Task<bool> HasChildrenAsync(Guid menuId)
    {
        return await _tb.AnyAsync(m => m.ParentId == menuId && !m.IsDeleted);
    }

    /// <summary>
    /// 检查菜单是否被角色使用
    /// </summary>
    public async Task<bool> IsUsedByRolesAsync(Guid menuId)
    {
        return await _db.GsRoleMenus
            .AnyAsync(rm => rm.MenuId == menuId && !rm.IsDeleted);
    }

    /// <summary>
    /// 获取菜单的角色数量
    /// </summary>
    public async Task<int> GetRoleCountAsync(Guid menuId)
    {
        return await _db.GsRoleMenus
            .Where(rm => rm.MenuId == menuId && !rm.IsDeleted)
            .CountAsync();
    }

    /// <summary>
    /// 更新菜单排序
    /// </summary>
    public async Task<bool> UpdateOrderAsync(Guid menuId, int order)
    {
        try
        {
            var menu = await _tb.FirstOrDefaultAsync(m => m.Id == menuId && !m.IsDeleted);
            if (menu == null)
            {
                return false;
            }

            menu.Order = order;
            menu.UpdatedAt = DateTime.UtcNow;

            await _db.SaveChangesAsync();
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 获取同级菜单的最大排序值
    /// </summary>
    public async Task<int> GetMaxOrderAsync(Guid? parentId)
    {
        var maxOrder = await _tb
            .Where(m => m.ParentId == parentId && !m.IsDeleted)
            .MaxAsync(m => (int?)m.Order);

        return maxOrder ?? 0;
    }
} 